/**
 * User: Ruslan Mikhaylenko mirunet@gmail.com
 * Date: 01.05.13
 * Time: 22:39
 */

import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.util.Collections;

public class FilesUtils {
    private static String[] extentions = {"avi", "mkv", "mp4"};
    private static boolean first_run = true;

    private static void erasefile(String filename) {
        try {
            File file = new File(filename);
            if (!file.exists()) {
                return;
            }
            if (!file.delete()) {
                System.out.println("Unable to delete file: " + filename);
                System.exit(1);
            }
            boolean success;
            success = new File(filename).createNewFile();
            if (!success) {
                System.out.println("*** Unable to create file: " + filename);
                System.exit(1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void insertrecord(String video_filename, String list_filename, String time_pos) {
        try {
            File file = new File(list_filename);
            checkfileavailability(list_filename);

            ArrayList<String> list = new ArrayList<>();
            String line;
            try (BufferedReader br = new BufferedReader(new FileReader(file))) {
                while ((line = br.readLine()) != null) {
                    list.add(line);
                }
            }

            FileWriter fileWritter = new FileWriter(file.getAbsolutePath(), false);
            try (BufferedWriter bufferWriter = new BufferedWriter(fileWritter)) {
                for (String ln : list) {
                    String[] fields = ln.split("[|]+");

                    if (fields[0].equals(video_filename)) {
                        bufferWriter.write(fields[0] + "|" + time_pos);
                    } else {
                        bufferWriter.write(ln);
                    }
                    bufferWriter.newLine();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void addrecord(String video_filename, String list_filename) {
        try {
            File file = new File(list_filename);
            if (!file.exists()) {
                if (!file.createNewFile()) {
                    System.out.println("*** Unable to create a file" + list_filename);
                    System.exit(1);
                }

            }
            FileWriter fileWritter = new FileWriter(file.getAbsolutePath(), true);
            try (BufferedWriter bufferWritter = new BufferedWriter(fileWritter)) {
                bufferWritter.write(video_filename);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void makeplaylist(String dirname, String list_filename) {
        if (first_run) erasefile(list_filename);
        first_run = false;
        File dir_name = new File(dirname);
        if (!dir_name.isDirectory()) {
            System.out.println("*** Provided path: " + dirname + " is not a directory");
            System.exit(1);
        }
        File[] files = dir_name.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isFile()) {
                    int i = f.getName().lastIndexOf('.');
                    String file_extention = f.getName().substring(i + 1);

                    for (String ext : extentions) {
                        if (file_extention.equals(ext)) {
                            addrecord(f.getAbsolutePath() + "|ANS_time_pos=0\n", list_filename);
                        }
                    }

                } else if (f.isDirectory()) {
                    makeplaylist(f.getAbsolutePath(), list_filename);
                }
            }
        }
    }

    public static void create_playlist_dir(String dirname) {
        File dir_name = new File(dirname);
        boolean is_created = false;
        if (dir_name.isDirectory()) return;
        try {
            is_created = dir_name.mkdir();
        } catch (SecurityException e) {
            System.out.println("*** Unable to create a directory" + dirname);
            e.printStackTrace();
            System.exit(1);
        }
        // Just to be shure...
        if (!is_created) {
            System.out.println("*** Unable to create a directory " + dirname);
            System.exit(1);
        }
    }



    public static void sortplaylist(String list_filename) {
        try {
            File file = new File(list_filename);
            checkfileavailability(list_filename);

            ArrayList<String> list = new ArrayList<>();
            String line;
            try (BufferedReader br = new BufferedReader(new FileReader(file))) {
                while ((line = br.readLine()) != null) {
                    list.add(line);
                }
            }
            Collections.sort(list);

            FileWriter fileWritter = new FileWriter(file.getAbsolutePath(), false);
            try (BufferedWriter bufferWriter = new BufferedWriter(fileWritter)) {
                for (String ln : list) {
                    bufferWriter.write(ln);
                    bufferWriter.newLine();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void checkfileavailability(String filename) {
        File file = new File(filename);
        if (!file.exists()) {
            System.out.println("*** Unable to open a file " + filename);
            System.exit(1);
        }
    }

    public static ArrayList<String> getPlaylist(String fullPlaylistPath) {
        ArrayList<String> list = new ArrayList<>();
        FilesUtils.checkfileavailability(fullPlaylistPath);
        File file = new File(fullPlaylistPath);
        String line;
        int index = 0;

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {

            while ((line = br.readLine()) != null) {
                list.add(line);
                String[] fields = line.split("[|]+");
                if (!fields[1].equals("ANS_time_pos=0"))
                    index = list.size() - 1;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (index > 0) {
            for (int i = 0; i < index; i++) {
                list.remove(0);
            }
        }

        Collections.sort(list);
        return list;
    }
}
